package com.example.lwx.contentProvider;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.example.lwx.R;

public class ContProviderActivity extends Activity {
    Button bt_read;
    TextView tv_show;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==1){
            if(grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                smsRead();
            }else {
                Toast.makeText(ContProviderActivity.this,"权限申请失败",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void smsRead() {
        Uri uri=Uri.parse("content://sms/");
        ContentResolver contentResolver=getContentResolver();
        Cursor cursor=contentResolver.query(uri,new String[]{"_id","address","body"},null,null,null);
        if(cursor!=null&&cursor.getCount()>0){
            while (cursor.moveToNext()){
                int id=cursor.getInt(0);
                String address=cursor.getString(1);
                String body=cursor.getString(2);
                tv_show.append("\n手机号码："+address+"\n短信内容"+body+"\n");
            }
            cursor.close();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message___8);
        bt_read=findViewById(R.id.bt_read);
        tv_show=findViewById(R.id.tv_show);
        bt_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(ContProviderActivity.this,new String[]{Manifest.permission.READ_SMS},1);
            }
        });
    }

}
























